package logic

import (
	"context"
	"crypto/sha512"
	"fmt"
	"github.com/anaskhan96/go-password-encoder"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/metadata"
	"google.golang.org/grpc/status"
	"user_srv/model/mysql"
	"user_srv/user_proto"
)

type Server struct {
	user_proto.UnimplementedUserServer
}

func (s *Server) UserRegister(ctx context.Context, in *user_proto.UserRegisterRequest) (*user_proto.UserRegisterResponse, error) {
	incomingContext, b := metadata.FromIncomingContext(ctx)
	if b {
		fmt.Println(incomingContext)
	}

	_, err := mysql.GetUserByMobile(in.Mobile)
	if err != nil {
		return nil, status.Error(codes.Internal, "用户已注册")
	}
	options := &password.Options{10, 10000, 50, sha512.New}
	salt, encodedPwd := password.Encode(in.Password, options)
	u := mysql.User{
		NickName: in.NickName,
		Mobile:   in.Mobile,
		Password: fmt.Sprintf("$pbkdf2-sha512$%s$%s", salt, encodedPwd),
	}
	register, err := u.Register()
	if err != nil {
		return nil, status.Error(codes.Internal, "注册用户失败")
	}
	return &user_proto.UserRegisterResponse{
		Id:       int64(register.ID),
		NickName: register.NickName,
		Mobile:   register.Mobile,
		Password: register.Password,
	}, nil
}
